package Work;

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.TableModelEvent;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

public class StudentManagementSystem extends JFrame {
    private JTabbedPane tabbedPane;//定义一个选项卡模板
    private DefaultListModel<String> classListModel;//定义一个列表模型
    private DefaultListModel<String> groupListModel;
    private DefaultListModel<String> studentListModel;
    private JList<String> classList;//定义列表组件
    private JList<String> groupList;
    private JList<String> studentList;
    private Map<String, List<String>> classGroups;//定义数据结构
    private Map<String, List<String>> groupStudents;
    private Map<String, Map<String, Double>> studentScores; // 学生成绩映射表 <学生名称, <科目, 分数>>
    private JTable scoreTable; // 成绩表格
    private DefaultTableModel scoreTableModel; // 表格数据模型

    private Map<String, String> groupClassMap; // 小组与班级的映射
    private Map<String, String> studentGroupMap; // 学生与小组的映射

    public StudentManagementSystem() {
        setTitle("学生管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作

        // 初始化数据结构
        classListModel = new DefaultListModel<>();
        groupListModel = new DefaultListModel<>();
        studentListModel = new DefaultListModel<>();
        classGroups = new HashMap<>();
        groupStudents = new HashMap<>();
        studentScores = new HashMap<>();
        groupClassMap = new HashMap<>();
        studentGroupMap = new HashMap<>();

        // 创建选项卡面板
        tabbedPane = new JTabbedPane();

        // 添加各个管理模块
        tabbedPane.addTab("班级管理", createClassPanel());
        tabbedPane.addTab("小组管理", createGroupPanel());
        tabbedPane.addTab("学生管理", createStudentPanel());
        tabbedPane.addTab("随机点名", createRandomPanel());
        tabbedPane.addTab("成绩管理", createScorePanel());
        //将选项卡面板添加到主窗口
        add(tabbedPane);
        //设置窗口居中显示
        setLocationRelativeTo(null);
    }

    /**
     * 创建班级面板
     * 此方法用于生成一个包含班级列表和操作按钮的面板用户可以通过这个面板来新增或删除班级
     * @return JPanel 返回包含班级列表和操作按钮的面板
     */
    private JPanel createClassPanel() {
        // 创建一个使用BorderLayout布局的面板
        JPanel panel = new JPanel(new BorderLayout());

        // 创建班级列表和其模型，并添加到滚动面板中
        classList = new JList<>(classListModel);
        JScrollPane scrollPane = new JScrollPane(classList);

        // 创建包含按钮的面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增班级");
        JButton deleteButton = new JButton("删除班级");

        // 新增班级按钮的事件监听器
        addButton.addActionListener(e -> {
            // 提示用户输入班级名称
            String className = JOptionPane.showInputDialog("请输入班级名称：");
            // 如果用户输入了班级名称且不为空，则添加到班级列表模型中，并在班级分组中创建对应的空列表
            if (className != null && !className.trim().isEmpty()) {
                classListModel.addElement(className);
                classGroups.put(className, new ArrayList<>());
            }
        });

        // 删除班级按钮的事件监听器
        deleteButton.addActionListener(e -> {
            // 获取当前选中的班级索引
            int selectedIndex = classList.getSelectedIndex();
            // 如果有班级被选中，则从模型中移除该班级，并从班级分组中移除对应的列表
            if (selectedIndex != -1) {
                String className = classListModel.getElementAt(selectedIndex);
                classListModel.remove(selectedIndex);
                classGroups.remove(className);
            }
        });

        // 将按钮添加到按钮面板中
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);

        // 将滚动面板和按钮面板添加到主面板中
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 返回包含班级列表和操作按钮的面板
        return panel;
    }

    private JPanel createGroupPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        groupList = new JList<>(groupListModel);
        JScrollPane scrollPane = new JScrollPane(groupList);

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增小组");
        JButton deleteButton = new JButton("删除小组");

        addButton.addActionListener(e -> {
            String selectedClass = classList.getSelectedValue();
            if (selectedClass == null) {
                JOptionPane.showMessageDialog(this, "请先选择班级！");
                return;
            }

            String groupName = JOptionPane.showInputDialog("请输入小组名称：");
            if (groupName != null && !groupName.trim().isEmpty()) {
                groupListModel.addElement(groupName);
                classGroups.get(selectedClass).add(groupName);
                groupStudents.put(groupName, new ArrayList<>());
                groupClassMap.put(groupName, selectedClass);
            }
        });

        deleteButton.addActionListener(e -> {
            int selectedIndex = groupList.getSelectedIndex();
            if (selectedIndex != -1) {
                String groupName = groupListModel.getElementAt(selectedIndex);
                groupListModel.remove(selectedIndex);
                groupStudents.remove(groupName);
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        return panel;
    }

    private JPanel createStudentPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        studentList = new JList<>(studentListModel);
        JScrollPane scrollPane = new JScrollPane(studentList);

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增学生");
        JButton deleteButton = new JButton("删除学生");

        addButton.addActionListener(e -> {
            String selectedGroup = groupList.getSelectedValue();
            if (selectedGroup == null) {
                JOptionPane.showMessageDialog(this, "请先选择小组！");
                return;
            }

            String studentName = JOptionPane.showInputDialog("请输入学生姓名+学号：");
            if (studentName != null && !studentName.trim().isEmpty()) {
                studentListModel.addElement(studentName);
                groupStudents.get(selectedGroup).add(studentName);
                studentGroupMap.put(studentName, selectedGroup);
            }
        });

        deleteButton.addActionListener(e -> {
            int selectedIndex = studentList.getSelectedIndex();
            if (selectedIndex != -1) {
                String studentName = studentListModel.getElementAt(selectedIndex);
                studentListModel.remove(selectedIndex);
                // 从成绩记录中也删除该学生
                studentScores.remove(studentName);
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        return panel;
    }

    private JPanel createRandomPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        JPanel buttonPanel = new JPanel();
        JTextArea resultArea = new JTextArea(10, 40);
        resultArea.setEditable(false);

        JButton randomClassButton = new JButton("随机抽取班级");
        JButton randomGroupButton = new JButton("随机抽取小组");
        JButton randomStudentButton = new JButton("随机抽取学生");

        randomClassButton.addActionListener(e -> {
            if (classListModel.isEmpty()) {
                resultArea.setText("没有可用的班级！");
                return;
            }
            int index = new Random().nextInt(classListModel.getSize());
            resultArea.setText("随机抽取的班级：" + classListModel.getElementAt(index));
        });

        randomGroupButton.addActionListener(e -> {
            if (groupListModel.isEmpty()) {
                resultArea.setText("没有可用的小组！");
                return;
            }
            int index = new Random().nextInt(groupListModel.getSize());
            resultArea.setText("随机抽取的小组：" + groupListModel.getElementAt(index));
        });

        randomStudentButton.addActionListener(e -> {
            if (studentListModel.isEmpty()) {
                resultArea.setText("没有可用的学生！");
                return;
            }
            int index = new Random().nextInt(studentListModel.getSize());
            resultArea.setText("随机抽取的学生：" + studentListModel.getElementAt(index));
        });

        buttonPanel.add(randomClassButton);
        buttonPanel.add(randomGroupButton);
        buttonPanel.add(randomStudentButton);

        panel.add(new JScrollPane(resultArea), BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        return panel;
    }

    private JPanel createScorePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建表格模型
        String[] columnNames = {"学生姓名", "语文", "数学", "英语", "平均分"};
        scoreTableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column > 0; // 只允许编辑成绩列
            }
        };

        scoreTable = new JTable(scoreTableModel);
        JScrollPane scrollPane = new JScrollPane(scoreTable);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addScoreButton = new JButton("录入成绩");
        JButton calculateButton = new JButton("计算平均分");
        JButton exportButton = new JButton("导出成绩");

        // 录入成绩按钮事件
        addScoreButton.addActionListener(e -> {
            if (scoreTableModel == null) {
                JOptionPane.showMessageDialog(this, "表格初始化错误！");
                return;
            }

            String selectedStudent = studentList.getSelectedValue();
            if (selectedStudent == null) {
                JOptionPane.showMessageDialog(this, "请先选择学生！");
                return;
            }

            try {
                // 直接添加成绩记录，不进行存在性检查
                scoreTableModel.addRow(new Object[]{selectedStudent, "0", "0", "0", "0"});
                studentScores.put(selectedStudent, new HashMap<>());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "添加成绩记录时发生错误：" + ex.getMessage());
            }
        });

        // 计算平均分按钮事件
        calculateButton.addActionListener(e -> {
            if (scoreTableModel == null) {
                JOptionPane.showMessageDialog(this, "表格初始化错误！");
                return;
            }

            try {
                int rowCount = scoreTableModel.getRowCount();
                for (int i = 0; i < rowCount; i++) {
                    double chinese = getScoreValue(i, 1);
                    double math = getScoreValue(i, 2);
                    double english = getScoreValue(i, 3);
                    double average = (chinese + math + english) / 3.0;

                    // 更新成绩映射表
                    String studentName = (String) scoreTableModel.getValueAt(i, 0);
                    if (studentName != null) {
                        Map<String, Double> scores = studentScores.computeIfAbsent(studentName, k -> new HashMap<>());
                        scores.put("语文", chinese);
                        scores.put("数学", math);
                        scores.put("英语", english);
                        scores.put("平均分", average);

                        // 使用String.format确保数字格式正确
                        scoreTableModel.setValueAt(String.format("%.1f", chinese), i, 1);
                        scoreTableModel.setValueAt(String.format("%.1f", math), i, 2);
                        scoreTableModel.setValueAt(String.format("%.1f", english), i, 3);
                        scoreTableModel.setValueAt(String.format("%.1f", average), i, 4);
                    }
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "计算平均分时发生错误：" + ex.getMessage());
            }
        });

        // 导出成绩按钮事件
        exportButton.addActionListener(e -> {
            if (scoreTableModel == null) {
                JOptionPane.showMessageDialog(this, "表格初始化错误！");
                return;
            }

            try {
                StringBuilder report = new StringBuilder("成绩报告：\n\n");
                int rowCount = scoreTableModel.getRowCount();
                for (int i = 0; i < rowCount; i++) {
                    Object studentName = scoreTableModel.getValueAt(i, 0);
                    if (studentName != null) {
                        report.append("学生：").append(studentName).append("\n");
                        report.append("语文：").append(scoreTableModel.getValueAt(i, 1)).append("\n");
                        report.append("数学：").append(scoreTableModel.getValueAt(i, 2)).append("\n");
                        report.append("英语：").append(scoreTableModel.getValueAt(i, 3)).append("\n");
                        report.append("平均分：").append(scoreTableModel.getValueAt(i, 4)).append("\n\n");
                    }
                }

                JTextArea textArea = new JTextArea(report.toString());
                JScrollPane scrollPane2 = new JScrollPane(textArea);
                textArea.setEditable(false);
                JDialog dialog = new JDialog(this, "成绩报告", true);
                dialog.add(scrollPane2);
                dialog.setSize(400, 300);
                dialog.setLocationRelativeTo(this);
                dialog.setVisible(true);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "导出成绩时发生错误：" + ex.getMessage());
            }
        });

        // 添加表格编辑监听器
        scoreTable.getModel().addTableModelListener(e -> {
            if (e.getType() == TableModelEvent.UPDATE) {
                try {
                    int row = e.getFirstRow();
                    int column = e.getColumn();
                    if (column >= 1 && column <= 3) { // 只处理成绩列的更改
                        String studentName = (String) scoreTableModel.getValueAt(row, 0);
                        Map<String, Double> scores = studentScores.computeIfAbsent(studentName, k -> new HashMap<>());
                        double value = getScoreValue(row, column);
                        String subject = scoreTable.getColumnName(column);
                        scores.put(subject, value);

                        // 格式化显示的数值
                        scoreTableModel.setValueAt(String.format("%.1f", value), row, column);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "输入的成绩格式不正确，请输入数字！");
                }
            }
        });

        buttonPanel.add(addScoreButton);
        buttonPanel.add(calculateButton);
        buttonPanel.add(exportButton);

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    // 辅助方法：获取表格中的成绩值
    private double getScoreValue(int row, int column) {
        try {
            Object value = scoreTableModel.getValueAt(row, column);
            if (value == null || value.toString().trim().isEmpty()) {
                return 0.0;
            }
            return Double.parseDouble(value.toString().trim());
        } catch (Exception e) {
            return 0.0;
        }
    }
}